const axios = require('axios');
const fs = require('fs');
const path = require('path');

// API基础URL
const BASE_URL = 'http://localhost:3000/api/auth';

// 测试结果存储
const testResults = {
  timestamp: new Date().toISOString(),
  results: []
};

// 测试用的用户数据 - 添加时间戳避免重复
const timestamp = new Date().getTime();
const testUser = {
  username: `testuser_${timestamp}`,
  email: `testuser_${timestamp}@example.com`,
  password: 'Test@12345',
  newPassword: 'NewTest@12345'
};

let authToken = null;

/**
 * 记录测试结果
 */
function recordResult(testName, success, message) {
  const result = {
    testName,
    success,
    message,
    timestamp: new Date().toISOString()
  };
  testResults.results.push(result);
  console.log(`[${success ? '✓' : '✗'}] ${testName}: ${message}`);
  return result;
}

/**
 * 保存测试结果到文件
 */
async function saveTestResults() {
  const outputPath = path.join(__dirname, 'test_results.json');
  await fs.promises.writeFile(outputPath, JSON.stringify(testResults, null, 2));
  console.log(`\n测试结果已保存到: ${outputPath}`);
}

/**
 * 测试注册接口
 */
async function testRegister() {
  try {
    const response = await axios.post(`${BASE_URL}/register`, {
      username: testUser.username,
      email: testUser.email,
      password: testUser.password
    });
    
    if (response.status === 201) {
      return recordResult('注册接口', true, '注册成功: ' + JSON.stringify(response.data));
    } else {
      return recordResult('注册接口', false, `状态码错误: ${response.status}`);
    }
  } catch (error) {
    return recordResult('注册接口', false, `请求失败: ${error.response?.data?.message || error.message}`);
  }
}

/**
 * 测试登录接口
 */
async function testLogin() {
  try {
    const response = await axios.post(`${BASE_URL}/login`, {
      username: testUser.username,
      password: testUser.password
    });
    
    if (response.status === 200) {
      // 检查响应数据中是否有token字段或类似的认证信息
      if (response.data.token) {
        authToken = response.data.token;
        return recordResult('登录接口', true, '登录成功，已获取token');
      } else if (response.data.data && response.data.data.token) {
        authToken = response.data.data.token;
        return recordResult('登录接口', true, '登录成功，已获取token（嵌套在data中）');
      } else {
        authToken = response.data;
        return recordResult('登录接口', true, '登录成功，已获取响应数据');
      }
    } else {
      return recordResult('登录接口', false, `状态码错误: ${response.status}`);
    }
  } catch (error) {
    return recordResult('登录接口', false, `请求失败: ${error.response?.data?.message || error.message}`);
  }
}

/**
 * 测试获取用户信息接口
 */
async function testGetProfile() {
  try {
    if (!authToken) {
      return recordResult('获取用户信息接口', false, '未获取到认证token');
    }
    
    const response = await axios.get(`${BASE_URL}/profile`, {
      headers: {
        Authorization: `Bearer ${authToken}`
      }
    });
    
    if (response.status === 200) {
      return recordResult('获取用户信息接口', true, `获取成功，用户ID: ${response.data.id}`);
    } else {
      return recordResult('获取用户信息接口', false, `状态码错误: ${response.status}`);
    }
  } catch (error) {
    return recordResult('获取用户信息接口', false, `请求失败: ${error.response?.data?.message || error.message}`);
  }
}

/**
 * 测试修改密码接口
 */
async function testChangePassword() {
  try {
    if (!authToken) {
      return recordResult('修改密码接口', false, '未获取到认证token');
    }
    
    const response = await axios.put(`${BASE_URL}/change-password`, {
      oldPassword: testUser.password,
      newPassword: testUser.newPassword
    }, {
      headers: {
        Authorization: `Bearer ${authToken}`
      }
    });
    
    if (response.status === 200) {
      // 为了后续可能的测试，交换密码
      [testUser.password, testUser.newPassword] = [testUser.newPassword, testUser.password];
      return recordResult('修改密码接口', true, '密码修改成功');
    } else {
      return recordResult('修改密码接口', false, `状态码错误: ${response.status}`);
    }
  } catch (error) {
    return recordResult('修改密码接口', false, `请求失败: ${error.response?.data?.message || error.message}`);
  }
}

/**
 * 测试未认证访问需要认证的接口
 */
async function testUnauthorizedAccess() {
  try {
    const response = await axios.get(`${BASE_URL}/profile`);
    return recordResult('未授权访问测试', false, `应该被拒绝但返回了: ${response.status}`);
  } catch (error) {
    if (error.response && error.response.status === 401) {
      return recordResult('未授权访问测试', true, '正确拒绝了未授权访问');
    } else {
      return recordResult('未授权访问测试', false, `预期401但返回了: ${error.response?.status || '无响应'}`);
    }
  }
}

/**
 * 运行所有测试
 */
async function runAllTests() {
  console.log('开始测试认证接口...');
  console.log('='.repeat(50));
  
  try {
    // 1. 测试注册
    await testRegister();
    
    // 2. 测试登录
    await testLogin();
    
    // 3. 测试获取用户信息
    await testGetProfile();
    
    // 4. 测试修改密码
    await testChangePassword();
    
    // 5. 测试未授权访问
    await testUnauthorizedAccess();
    
    // 计算总体结果
    const totalTests = testResults.results.length;
    const passedTests = testResults.results.filter(r => r.success).length;
    const passRate = (passedTests / totalTests * 100).toFixed(2);
    
    console.log('='.repeat(50));
    console.log(`测试完成: ${passedTests}/${totalTests} 通过 (${passRate}%)`);
    
  } catch (error) {
    console.error('测试过程中发生错误:', error);
  } finally {
    // 保存测试结果
    await saveTestResults();
  }
}

// 运行测试
runAllTests();